package org.springframework.fusion.elasticsearch.controller;

import java.util.Date;
import java.util.Iterator;

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Order;
import org.springframework.fusion.elasticsearch.dao.UserRepository;
import org.springframework.fusion.elasticsearch.domain.User;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

	@Autowired
	private UserRepository userRepository;
	@Autowired
	private TransportClient transportClient;
	
	@GetMapping("test")
	public ResponseEntity<Page<User>> test(){
		System.out.println(transportClient);
		long time = new Date().getTime();
		User user = new User();
		user.setId(time);
		user.setTitle("可能的房价肯定福建东南分局看到");
		user.setContent("解放军的飞机的肌肤");
		user.setAge(new Date());
		userRepository.save(user);
		Pageable pageable = PageRequest.of(0, 10, Sort.by(Order.desc("id")));
		Page<User> findAll = userRepository.findAll(pageable);
		return ResponseEntity.ok(findAll);
	}
	
	@GetMapping("test2")
	public ResponseEntity<SearchHits> test2(){
		SearchResponse searchResponse = transportClient.prepareSearch("blog1").setTypes("article")
				.setQuery(QueryBuilders.matchAllQuery()).get();
		SearchHits hits = searchResponse.getHits();
		Iterator<SearchHit> iterator = hits.iterator();
		while (iterator.hasNext()) {
			SearchHit searchHit = iterator.next();
			String sourceAsString = searchHit.getSourceAsString();
			System.out.println(sourceAsString);
		}
		return ResponseEntity.ok(null);
	}
}
